package com.jianhua.backend.controller;

import com.jianhua.backend.common.R;
import com.jianhua.backend.domain.dto.UserDto;
import com.jianhua.backend.domain.entity.User;
import com.jianhua.backend.domain.vo.PageVo;
import com.jianhua.backend.service.UserService;
import com.jianhua.backend.utils.PasswordResetTokenStore;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 存储系统所有用户的基本信息，包括客户、后厨人员和管理员 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-02
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public R register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String securityQuestion,
            @RequestParam String securityAnswer) {

        User u = userService.findByUserName(username);
        if (u != null) {
            return R.error("用户被占用");
        }


        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 直接保存明文密码
        newUser.setSecurityQuestion(securityQuestion);
        newUser.setSecurityAnswer(securityAnswer); // 同样保存明文答案

        userService.register(newUser);

        return R.success("注册成功！");
    }
    @PostMapping("/get-security-question")
    public R<String> getSecurityQuestion(@RequestParam String username) {
        User user = userService.findByUserName(username);
        if (user == null) {
            return R.error("用户不存在");
        }
        return R.success(user.getSecurityQuestion());
    }
    @PostMapping("/verify-security-answer")
    public R<String> verifySecurityAnswer(
            @RequestParam String username,
            @RequestParam String answer) {

        User user = userService.findByUserName(username);
        if (user == null) {
            return R.error("用户不存在");
        }

        if (!answer.equals(user.getSecurityAnswer())) {
            return R.error("安全问题答案错误");
        }

        // 生成临时 token 或 session 标识，允许用户进入下一步
        String resetToken = UUID.randomUUID().toString();
        PasswordResetTokenStore.storeToken(user.getUserId(), resetToken);

        return R.success(resetToken); // 返回 token 用于后续验证
    }
    @PostMapping("/reset-password")
    public R<String> resetPassword(
            @RequestParam String token,
            @RequestParam String newPassword) {

        Integer userId = PasswordResetTokenStore.validateToken(token);
        if (userId == null) {
            return R.error("无效或过期的 token");
        }

        // 更新密码（建议加密）
        userService.updatePassword(userId, newPassword);

        PasswordResetTokenStore.removeToken(token);

        return R.success("密码重置成功");
    }

    @PostMapping("/login")
    public R login(@RequestParam String username,
                           @RequestParam String password) {
        User loginUser = userService.findByUserName(username);

        if (loginUser == null) {
            return R.error("用户名错误");
        }

        if (!password.equals(loginUser.getPassword())) {
            return R.error("密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginUser.getUserId());
        //String token = JwtUtil.generateToken(claims); // 假设 JwtUtil 已定义

        return R.success(loginUser);
    }

    /**
     * 获取用户列表接口
     * 根据传入的用户信息条件，查询并返回用户列表数据
     *
     * @param userDto 用户信息条件，包含查询所需的各种筛选条件
     * @return 返回包含用户列表的响应对象R
     */
    @GetMapping("/list")
    public R listUser(UserDto userDto){
        PageVo<User> userPageVo = userService.listUser(userDto);
        return R.success(userPageVo);
    }

    /**
     * 更新用户信息接口
     * 该接口用于更新用户的相关信息。
     *
     * @param user 要更新的用户信息，通过@RequestBody注解接收
     * @return 返回操作结果，成功则返回R.success(null)
     */
    @PostMapping("/update")
    public R updateUser(@RequestBody User user){
        userService.updateUser(user);
        return R.success(null);
    }

    @PostMapping("/get/{id}")
    public R getUserById(@PathVariable Integer id){
        User userById = userService.getUserById(id);
        return R.success(userById);
    }

    /**
     * 删除用户接口
     * 根据用户ID删除对应的用户数据
     *
     * @param id 用户ID
     * @return 操作成功的响应对象
     */
    @DeleteMapping("/delete/{id}")
    public R deleteUser(@PathVariable Integer id){
        userService.deleteUser(id);
        return R.success(null);
    }

}
